
package backupUtility;
import java.io.File;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.exception.ZipExceptionConstants;
/**
 * This class represents the main interface of the program
 * it also contains the main method for the whole project
 * @author Changcoco Kevin Paolo
 * @author Mamis Dominique Bernard
 * @author Palasi Jandy
 * @author Rafael Ian Paolo 
 */
public class BackupUtilityUI extends javax.swing.JFrame {

    public BackupUtilityUI() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        fileListGetter1 = new backupUtility.FileListGetter();
        jButton1 = new javax.swing.JButton();
        deleteBackupButton = new javax.swing.JButton();
        editBackupButton = new javax.swing.JButton();
        changePasswordButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);
        getContentPane().setLayout(null);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/backupUtility/create.jpg"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1);
        jButton1.setBounds(10, 210, 380, 110);

        deleteBackupButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/backupUtility/delete.jpg"))); // NOI18N
        deleteBackupButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteBackupButtonActionPerformed(evt);
            }
        });
        getContentPane().add(deleteBackupButton);
        deleteBackupButton.setBounds(10, 380, 380, 110);

        editBackupButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/backupUtility/atb.jpg"))); // NOI18N
        editBackupButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editBackupButtonActionPerformed(evt);
            }
        });
        getContentPane().add(editBackupButton);
        editBackupButton.setBounds(410, 210, 380, 110);

        changePasswordButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/backupUtility/cpass.jpg"))); // NOI18N
        changePasswordButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changePasswordButtonActionPerformed(evt);
            }
        });
        getContentPane().add(changePasswordButton);
        changePasswordButton.setBounds(410, 380, 370, 110);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/backupUtility/ass.jpg"))); // NOI18N
        getContentPane().add(jLabel1);
        jLabel1.setBounds(0, 0, 800, 600);

        setSize(new java.awt.Dimension(813, 617));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents
/**
* Executes the Loading User Interface and then disposes the frame
* @param java.qwt.event.ActionEvent evt
*/	
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            new Loading().setVisible(true);
        } catch (InterruptedException ex) {
            Logger.getLogger(BackupUtilityUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed
/**
  * This method is responsible for archiving the backup folder into a zip file. 
  * It also reads the file name and returns the zip file with the corresponding filename of the backup folder.
  * It asks for the current password and if the password is correct, you can enter the new password.
  * @param evt
  * @return chosen zip file.
  */
    private void changePasswordButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changePasswordButtonActionPerformed
      JOptionPane.showMessageDialog(null,"Choose zip Backup.");
      final JFileChooser fileChooser = new JFileChooser(new File("D:/BACKUP/"));
      fileChooser.setFileFilter(new FileFilter(){      
       public boolean accept(File f) {
          /**
           * It reads the file name and return the zip file
           * with the corresponding filename.ds
           * @param f
           * @return chosen zip file.
           */
            if (f.isDirectory()) {
                return true;
            }
            final String name = f.getName();
            return name.endsWith(".zip");
        }
  /** returns specific zipped backup folder */
        public String getDescription() {
            return "*.zip";
        }
    });
    fileChooser.showOpenDialog(this);
    File chosen = fileChooser.getSelectedFile();
    if(chosen!=null){
    String key = JOptionPane.showInputDialog("Enter old password: ");
          try {
             ZipFile zip = new ZipFile(chosen);
              if(zip.isEncrypted()){
                zip.setPassword(key);
              File location = fileChooser.getSelectedFile().getParentFile();
              String path = location.getPath();
              String newPass;
              try{
              newPass = JOptionPane.showInputDialog("Enter new Password: ");
              }catch(Exception e){
                  return;
              }
              if(newPass != null){
              zip.extractAll(path);
              chosen.delete();
              File [] extracted = location.listFiles();
              ArrayList<File> newZip = new ArrayList<File>();
              for(File f : extracted){
                   newZip.add(f);
              }
              ZipBackup zipper = new ZipBackup(newZip, path, chosen.getAbsolutePath(), newPass);
               for(File f : extracted){
                   f.delete();
              }
              JOptionPane.showMessageDialog(null,"Password has been changed.");
              }else{
                  return;
              }
            }
          } catch (ZipException ex) {

			JOptionPane.showMessageDialog(null, "Wrong password!!!");
                        return;
          }catch(Exception e){}
    }else{
    return;
    }    

    }//GEN-LAST:event_changePasswordButtonActionPerformed

    private void editBackupButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editBackupButtonActionPerformed
       JOptionPane.showMessageDialog(null,"Choose zip Backup.");
      final JFileChooser fileChooser = new JFileChooser(new File("D:/BACKUP/"));
      fileChooser.setFileFilter(new FileFilter(){      
       public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            }
            final String name = f.getName();
            return name.endsWith(".zip");
        }

        public String getDescription() {
            return "*.zip";
        }
    });
    fileChooser.showOpenDialog(this);
    File chosen = fileChooser.getSelectedFile();
    if(chosen!=null){
         String pass;
        try{
            pass = JOptionPane.showInputDialog("Enter password: ");
        }catch(Exception e){
            return;
           }
    if(pass==null){
        return;
     }else{
        boolean open=true;
             ArrayList<File> arrayListofFiles = new ArrayList<File>();
                try{
             ZipFile zip = new ZipFile(chosen);
              if(zip.isEncrypted()){
                zip.setPassword(pass);
                String path = chosen.getParentFile().getPath();
                zip.extractAll(path);
                 File[] listOfFiles = chosen.getParentFile().listFiles();
                  for(File f : listOfFiles){
                   arrayListofFiles.add(f);
              }
                  arrayListofFiles.remove(chosen);
              }
         }catch(ZipException ex) {
			JOptionPane.showMessageDialog(null, "Wrong password!!!");
                          open=false;
          }catch(Exception e){}
    if(open){
    new EditBackupUI(chosen, arrayListofFiles, pass).setVisible(true);
    dispose();
    }
    return;
    }
    }
    }//GEN-LAST:event_editBackupButtonActionPerformed

/**
 * 
 * Chooses a file, asks the user a password.
 * When the password is correct the delete will be allowed.
 * If it is un correct then a message will appear saying the password is wrong.
 * @param evt 
 * @exception ZipException ex
 */
    private void deleteBackupButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteBackupButtonActionPerformed
        JOptionPane.showMessageDialog(null,"Choose zip Backup.");
        final JFileChooser fileChooser = new JFileChooser(new File("D:/BACKUP/"));
        fileChooser.setFileFilter(new FileFilter(){
            public boolean accept(File f) {
                if (f.isDirectory()) {
                    return true;
                }
                final String name = f.getName();
                return name.endsWith(".zip");
            }

            public String getDescription() {
                return "*.zip";
            }
        });
        fileChooser.showOpenDialog(this);
        File chosen = fileChooser.getSelectedFile();
        if(chosen!=null){
        String pass = JOptionPane.showInputDialog("Enter password: ");
        try {
            ZipFile zip = new ZipFile(chosen);
            if(zip.isEncrypted()){
                zip.setPassword(pass);
                File location = fileChooser.getSelectedFile().getParentFile();
                String path = location.getPath();
                zip.extractAll(path);
                chosen.delete();
                File [] extracted = location.listFiles();
                ArrayList<File> newZip = new ArrayList<File>();
                for(File f : extracted){
                    f.delete();
                }
                location.delete();
                JOptionPane.showMessageDialog(null,"Successfully Deleted Backup.");
            }
        } catch (ZipException ex) {

            JOptionPane.showMessageDialog(null, "Wrong password!!!");
            return;
        }catch(Exception e){}
        
        }else{
            return;
        }
    }//GEN-LAST:event_deleteBackupButtonActionPerformed
/**
 * Main method for the interface. Executes the interface when the
 * countdown finishes
 * @param args 
 * @exception exc
 */
    public static void main(String args[]) {

        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BackupUtilityUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BackupUtilityUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BackupUtilityUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BackupUtilityUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
       
       //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BackupUtilityUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BackupUtilityUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BackupUtilityUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BackupUtilityUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        try {
            for(int s=3;s>=0;s--){
      		Thread.sleep(1000);
      		if (s == 0) {
                    int n = JOptionPane.showConfirmDialog(null,"It's almost time. Would you like to back up your files?","",JOptionPane.YES_NO_OPTION);		
                        if(n == JOptionPane.YES_OPTION){
                            java.awt.EventQueue.invokeLater(new Runnable() {
                                public void run() {
                                new BackupUtilityUI().setVisible(true);
                                }});
                        }
                        else{
                            System.exit(0);
                        }
                 }

   		}
        } catch(Exception exc) {}
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton changePasswordButton;
    private javax.swing.JButton deleteBackupButton;
    private javax.swing.JButton editBackupButton;
    private backupUtility.FileListGetter fileListGetter1;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration//GEN-END:variables
}
